// https://www.lintcode.com/problem/clone-graph

/**
 * Definition for Undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     List<UndirectedGraphNode> neighbors;
 *     UndirectedGraphNode(int x) {
 *         label = x;
 *         neighbors = new ArrayList<UndirectedGraphNode>();
 *     }
 * }
 */

public class Solution {
    /**
     * @param node: A undirected graph node
     * @return: A undirected graph node
     */
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        // write your code here
        Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<>();
        return _cloneGraph(node, map);
    }

    protected UndirectedGraphNode _cloneGraph(UndirectedGraphNode node, Map<UndirectedGraphNode, UndirectedGraphNode> map) {
        if (node == null) {
            return null;
        }
        if (map.containsKey(node)) {
            return map.get(node);
        }
        UndirectedGraphNode ret = new UndirectedGraphNode(node.label);
        map.put(node, ret);
        for (UndirectedGraphNode neighbor : node.neighbors) {
            ret.neighbors.add(_cloneGraph(neighbor, map));
        }
        return ret;
    }
}